# -*- coding: UTF-8 -*-
import functools
import time

from flow_alchemy.core.context import TaskContext
from flow_alchemy.core.globals import session
from flow_alchemy.db.models import Task
from flow_alchemy.db.work_status import TaskStatus
from flow_alchemy.util.decorator import call_time
from flow_alchemy.util.suspend import Suspend

__version__ = "0.1.0"
__author__ = 'yinpli'
__date__ = '2021-04-03'


def get_version():
    return __version__


platform = 'mysql'


class FlowAlchemy(object):
    def __init__(self, suspend=None):
        self.suspend = suspend if suspend else Suspend(expect=10)

    @call_time
    def play(self, task_id):
        if task_id:
            with TaskContext(tid=task_id) as context:
                context.begin()
        session.commit()

    def next(self):
        task = session.query(Task).filter(Task.status == TaskStatus.init).order_by(Task.update_date.asc()).first()
        return task.tid if task else 0

    def loop(self):
        while True:
            task_id = self.next()
            item=self.play(task_id)
            self.suspend.add(item).sleep()